const app = getApp();

export default init;

function init() {
  this.listParams = {};
  this.header = {};
  this.listDataInit = listDataInit;
  this.pageListInit = pageListInit;
  this.getPageList = getPageList;
  this.onReachBottom = onReachBottom;
  this.onPullDownRefresh = onPullDownRefresh;
  this.func = func;
}

function func() {
  const that = this;
  return {
    listParams: that.listParams,
    listDataInit: that.listDataInit,
    pageListInit: that.pageListInit,
    getPageList: that.getPageList,
    onReachBottom: that.onReachBottom,
    onPullDownRefresh: that.onPullDownRefresh,
  }
}

function listDataInit() {
  const that = this;
  that.setData({
    lists: [], //列表数据
    msg: '请稍等...', //提示信息
    footMsg: "没有更多数据啦！", //底部提示信息
  })

  that.listParams.keyword = ''; //搜索框输入值
  that.listParams.page = 1; //当前页数
  that.listParams.row = 10; //1页的条数
  that.listParams.limit = 10; //1页的条数（兼容不同列表接口的）
  that.listParams.isReach = false; //是否全部加载完毕
  return true;
}

function pageListInit() {
  const that = this;
  that.listDataInit();
  that.getPageList();
  return true;
}

/**
 * 获取列表
 * param isReachBottom [Boolean] 是否上拉加载触发
 */
function getPageList(isReachBottom) {
  var that = this;
  var lists = that.data.lists;
  var listParams = that.listParams;
  var page = listParams.page;
  var row = listParams.row;
  var isReach = listParams.isReach;
  var header = that.header // 请求头
  var footMsg = "";

  if (isReachBottom) {
    if (isReach) return false;
    page++;
  }

  if (page == 1) {
    lists = [];
  }

  listParams.pageSize = row;
  listParams.pageNum = page;
  listParams.limit = row;

  app.middleware.requestAjax({
    serAddr: that.reqUrl,
    data: listParams,
    header: header,
    cancelToast: true,
    success: function(res) {
      console.log(res)
      var tempLists = res.data || [];

      if (row <= tempLists.length) {
        isReach = false;
        footMsg = "上拉加载更多";
      } else {
        isReach = true;
        footMsg = "没有更多数据啦！";
      }
      that.setData({
        msg: "",
        lists: lists.concat(tempLists),
        footMsg: footMsg,
      })
      that.listParams.page = page;
      that.listParams.isReach = isReach;

      if (that.callBack) that.callBack(res, lists);
      if (that.firstCallBack && page == 1) that.firstCallBack(res);
    },
    fail: function(res) {

      if (isReachBottom) {
        that.setData({
          footMsg: res && res.msg || "加载失败",
        })
      } else {
        that.setData({
          msg: res && res.msg || "加载失败",
        })
      }

    }
  })
}

function onReachBottom() {
  const that = this;
  // console.log("onReachBottom")
  that.getPageList(true);
}

function onPullDownRefresh() {
  const that = this;
  that.listParams.keyword = ''; //搜索框输入值
  that.listParams.page = 1; //当前页数
  that.listParams.row = 10; //1页的条数
  that.listParams.isReach = false; //是否全部加载完毕
  that.getPageList();
  wx.stopPullDownRefresh();
}